package com.magicborrow.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.adapter.SearchHistoryAdapter;
import com.magicborrow.beans.StuffListBean;
import com.magicborrow.fragment.SearchEmptyFragment;
import com.magicborrow.fragment.SearchResultFilterFragment;
import com.magicborrow.utils.SearchHistoryUtils;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by River on 5/12/16.
 */
public class SearchActivity extends BaseActivity implements VolleyTool.HTTPListener{

    private SearchResultFilterFragment mResultFragment;
    private SearchEmptyFragment mEmptyFragment;
    private EditText editSearch;
    private TextView search;
    public String content;
    private ListView mListView;
    private ArrayList<String> searchHitory;
    private SearchHistoryAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_activity);
        initView();
        initData();
        initListener();
        showListView();
    }

    private void initView(){
        editSearch = (EditText) findViewById(R.id.editSearch);
        search = (TextView)findViewById(R.id.search);
        mListView = (ListView)findViewById(R.id.listView);

    }

    private void initData(){
        mResultFragment = new SearchResultFilterFragment();
        mEmptyFragment = new SearchEmptyFragment();
        searchHitory = SearchHistoryUtils.getSearchHistory(this);
        if(searchHitory != null){
            final View view = LayoutInflater.from(this).inflate(R.layout.history_search_footview,null);
            (view.findViewById(R.id.clear)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    searchHitory.clear();
                    adapter.notifyDataSetChanged();
                    mListView.removeFooterView(view);
                    SearchHistoryUtils.saveSearchHistory(SearchActivity.this,null);
                }
            });
            mListView.addFooterView(view);
        }else{
            searchHitory = new ArrayList<>();
        }
        adapter = new SearchHistoryAdapter(this);
        adapter.setData(searchHitory);
        mListView.setAdapter(adapter);
    }

    private void showListView(){
        if(mListView.getVisibility() == View.VISIBLE){
            mListView.setVisibility(View.GONE);
        }else{
            mListView.setVisibility(View.VISIBLE);
        }
    }

    private void initListener(){
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveHistory();
                searchResult();
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                editSearch.setText(adapter.getData().get(position));
                content = adapter.getData().get(position);
                showListView();
                searchResult();
            }
        });

    }

    private void saveHistory(){
        content = editSearch.getText().toString();
        if(TextUtils.isEmpty(content)){return;}
        ArrayList<String> history = SearchHistoryUtils.getSearchHistory(SearchActivity.this);
        if(history == null){
            history = new ArrayList<>();
            history.add(0,content);
        }else{
            for (int i=0;i<history.size();i++){
                if(content.equals(history.get(i))){
                    history.remove(history.get(i));
                }
            }
            history.add(0,content);
        }
        SearchHistoryUtils.saveSearchHistory(SearchActivity.this,history);
        if(adapter.getData() != null){
            adapter.getData().clear();
        }
        adapter.setData(history);
        adapter.notifyDataSetChanged();
    }

    private void searchResult(){
        Map<String,String> params = new HashMap<>();
        params.put("page","0");
        params.put("size","10");
        params.put("kw",content);
        params.put("type","0");
        VolleyTool.get(Constants.SEARCH_URL,params,this,0,StuffListBean.class);
    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        mListView.setVisibility(View.GONE);
        StuffListBean bean = (StuffListBean)t;
        if(bean.getCode() == 0){
            if(bean.getData().getContent().size() > 0){
                showFragment(mResultFragment);
            }else{
                showFragment(mEmptyFragment);
            }
        }else{
            showShortMsg(bean.getMessage());
        }
    }

    private void showFragment(Fragment fragment){
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if(fragment instanceof SearchResultFilterFragment){
            if(!mResultFragment.isAdded()){
                transaction.hide(mEmptyFragment).add(R.id.fragmentContainer,mResultFragment).show(mResultFragment).commit();
            }else{
                transaction.hide(mEmptyFragment).show(mResultFragment).commit();
                mResultFragment.onRefresh(content);
            }
        }else{
            if(!mEmptyFragment.isAdded()){
                transaction.hide(mResultFragment).add(R.id.fragmentContainer,mEmptyFragment).show(mEmptyFragment).commit();
            }else{
                transaction.hide(mResultFragment).show(mEmptyFragment).commit();
            }
        }
    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {
        showShortMsg("服务器忙");
    }

}
